package cn.javabb.core.plugin.pay;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.javabb.common.utils.HttpUtil;
import cn.javabb.common.utils.ImageUtils;
import cn.javabb.core.plugin.pay.model.PayModel;
import com.alibaba.druid.util.StringUtils;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author javabb
 * @Date 2019/8/6 0006 下午 10:11
 * @Desc
 */
public class PayUtil {

    private static final String CREATE_ORDER_URL = "http://www.19fk.com/apisubmit";
    private static final String QUERY_ORDER_URL = "http://www.19fk.com/apiorderquery";
    private static final String version = "1.0";
    private static final Integer customerid = 20083642;
    private static final String notifyurl = "http://localhost:8086/call";
    private static final String returnurl = "http://localhost:8086/call";
    private static final String server = "";
    private static final String remark = "test";
    private static final String userKey = "4a94ed98b107f9cf13918dedfcaeab45f3ed6f00";

    public static PayModel createOrder(Double money, String paytype) throws Exception {
        Map<String, Object> param = new HashMap<>();
        // 根据日期来生成订单号
        String orderNo = DateUtil.format(new Date(), "yyyyMMddHHmmssSSS");
        if (StringUtils.isEmpty(paytype)) {
            paytype = "alipay";
        }
        param.put("version", version);
        param.put("customerid",customerid);
        param.put("sdorderno",orderNo);
        param.put("total_fee",money);
        param.put("bankcode","");
        param.put("paytype",paytype); //alipay  weixin
        param.put("notifyurl",URLEncoder.encode(notifyurl,"UTF-8"));
        param.put("returnurl",URLEncoder.encode(returnurl,"UTF-8"));
        param.put("remark",remark);

        String sign = "version="+version+"&customerid="+customerid+"&total_fee="+money
                +"&sdorderno="+orderNo+"&notifyurl="+notifyurl
                +"&returnurl="+returnurl+"&"+userKey;

        String md5Str = getMD5(sign);
        param.put("sign",md5Str);
        System.out.println(param.toString());
        /*String url = CREATE_ORDER_URL
                +"?version="+version
                +"&customerid="+customerid
                +"&sdorderno="+orderNo
                +"&total_fee="+money
                +"&bankcode="+""
                +"&paytype="+paytype
                +"&notifyurl="+URLEncoder.encode(notifyurl,"UTF-8")
                +"&returnurl="+URLEncoder.encode(returnurl,"UTF-8")
                +"&remark="+remark
                +"&sign="+md5Str;*/
        //不要用hutool的Http工具
        String res = HttpUtil.doPost(CREATE_ORDER_URL,param);
        System.out.println(res);
        //String res = RestClientUtil.post(CREATE_ORDER_URL,param,null);
        PayModel payModel = null;
        if(res.indexOf("img")>0 && res.indexOf("订单号码")>0){
            payModel = new PayModel()
                    .setMoney(money)
                    .setNotifyurl(notifyurl)
                    .setReturnUrl(returnurl)
                    .setPaytype(paytype)
                    .setOrderId(orderNo);
            if("alipay".equals(paytype)){
                payModel.setQr(ImageUtils.getImage(res).substring(25));
            }else{
                payModel.setQr(ImageUtils.getImage(res));
            }
        }
        //System.out.println(payModel);
        return payModel;
    }

    public static boolean queryOrder(String orderNo){
        String reqtime = DateUtil.format(new Date(),"yyyymmddhhmmss");
        Map<String, Object> param = new HashMap<>();
        param.put("customerid", customerid);
        param.put("sdorderno", orderNo);
        param.put("reqtime",reqtime);

        String signStr = "customerid="+customerid+"&sdorderno="+orderNo+"&reqtime="+reqtime+"&"+userKey;
        param.put("sign", getMD5(signStr));
        String res = HttpUtil.doPost(QUERY_ORDER_URL,param);
        System.out.println(res);
        JSONObject json = JSONUtil.parseObj(res);
        if (null != json && "1".equals(json.get("status").toString())) {
            return true;
        }
        return false;
    }


    /**
     * 获取MD5加密后的字符串，只能通过这种方式获取md5,其他所有的加密都没用
     * @param str 明文
     * @return 加密后的字符串
     * @throws Exception
     */
    public static String getMD5(String str) {
        /** 创建MD5加密对象 */
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            /** 进行加密 */
            md5.update(str.getBytes());
            /** 获取加密后的字节数组 */
            byte[] md5Bytes = md5.digest();
            String res = "";
            for (int i = 0; i < md5Bytes.length; i++){
                int temp = md5Bytes[i] & 0xFF;
                if (temp <= 0XF){ // 转化成十六进制不够两位，前面加零
                    res += "0";
                }
                res += Integer.toHexString(temp);
            }
            return res;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
    }
}
